<template>
  <a-collapse v-model:activeKey="vdata.activeKey" ghost accordion default-active-key="1">
    <a-collapse-panel key="1" header="服务商【三方应用】参数配置">
      <a-form ref="formRef" :model="vdata.currentConfig" layout="vertical" :rules="vdata.formRules">
        <a-row :gutter="16">
          <a-col span="24">
            <a-form-item label="环境配置" name="sandbox">
              <a-radio-group v-model:value="vdata.currentConfig['sandbox']">
                <a-radio :value="1">沙箱环境</a-radio>
                <a-radio :value="0">生产环境</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item label="合作伙伴身份（PID）" name="pid">
              <a-input v-model:value.trim="vdata.currentConfig['pid']" placeholder="请输入PID" @change="changeFun('pid')" />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item label="应用AppID" name="appId">
              <a-input v-model:value.trim="vdata.currentConfig['appId']" placeholder="请输入appId" @change="changeFun('appId')" />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="应用私钥（该字段必填）" name="privateKey">
              <a-textarea v-model:value="vdata.currentConfig.privateKey" :placeholder="vdata.encryptionField.privateKey || '请输入应用私钥'" type="textarea" @change="changeFun('privateKey')" />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="支付宝公钥" name="alipayPublicKey">
              <a-textarea v-model:value="vdata.currentConfig.alipayPublicKey" :placeholder="vdata.encryptionField.alipayPublicKey || '请输入支付宝公钥'" type="textarea" @change="changeFun('alipayPublicKey')" />
            </a-form-item>
          </a-col>
          <a-col span="12">
            <a-form-item label="接口签名方式(推荐使用RSA2)" name="signType">
              <a-radio-group v-model:value="vdata.currentConfig['signType']">
                <a-radio value="RSA">RSA</a-radio>
                <a-radio value="RSA2">RSA2</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="公钥证书" name="useCert">
              <a-radio-group v-model:value="vdata.currentConfig['useCert']">
                <a-radio :value="1">使用证书（请使用RSA2私钥）</a-radio>
                <a-radio :value="0">不使用证书</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="应用公钥证书（.crt格式）" name="appPublicCert">
              <JeepayUpload v-model:src="vdata.currentConfig.appPublicCert" bizType="cert" fileType="file" accept=".crt" />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="支付宝公钥证书（.crt格式）" name="alipayPublicCert">
              <JeepayUpload v-model:src="vdata.currentConfig.alipayPublicCert" bizType="cert" fileType="file" accept=".crt" />
            </a-form-item>
          </a-col>
          <a-col span="24">
            <a-form-item label="支付宝根证书（.crt格式）" name="alipayRootCert">
              <JeepayUpload v-model:src="vdata.currentConfig.alipayRootCert" bizType="cert" fileType="file" accept=".crt" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-collapse-panel>
  </a-collapse>
</template>
<script setup lang="ts">
import { ref, reactive, defineExpose } from 'vue'

const vdata = reactive ({
  ifDefineArray: [], // 接口的配置定义项数组
  currentConfig: {} as any, // 当前配置项
  activeKey: ['1'], // 折叠默认展开
  encryptionField : { // 定义加密的字段
    privateKey: '',
    alipayPublicKey: ''
  },
  //表单规则
  formRules: {
    pid: [{required: true, message: '请输入合作伙伴身份（PID）', trigger: 'blur'}],
    appId: [{required: true, message: '请输入应用AppID', trigger: 'blur'}],
    sandbox: [{required: true, type: 'number', message: '请选择环境', trigger: 'blur'}],
    signType: [{required: true, message: '请选择接口签名方式', trigger: 'blur'}],
    useCert: [{required: true, type: 'number', message: '请选择是否使用证书', trigger: 'blur'}],
    privateKey: [{
      trigger: 'blur', validator: (rule, value) => {
        if (!vdata.encryptionField[rule.field] && !value) {
          return Promise.reject(new Error('请输入应用私钥'))
        }
        return Promise.resolve()
      }
    }],
    alipayPublicKey: [{
      trigger: 'blur', validator: (rule, value) => {
        if (vdata.currentConfig['useCert'] === 0 && !vdata.encryptionField[rule.field] && !value) {
          return Promise.reject(new Error('请输入支付宝公钥'))
        }
        return Promise.resolve()
      }
    }],
    appPublicCert: [{
      trigger: 'blur', validator: (rule, value) => {
        if (vdata.currentConfig['useCert'] === 1 && !value) {
          return Promise.reject(new Error('请上传应用公钥证书（.crt格式）'))
        }
        return Promise.resolve()
      }
    }],
    alipayPublicCert: [{
      trigger: 'blur', validator: (rule, value) => {
        if (vdata.currentConfig['useCert'] === 1 && !value) {
          return Promise.reject(new Error('请上传支付宝公钥证书（.crt格式）'))
        }
        return Promise.resolve()
      }
    }],
    alipayRootCert: [{
      trigger: 'blur', validator: (rule, value) => {
        if (vdata.currentConfig['useCert'] === 1 && !value) {
          return Promise.reject(new Error('请上传支付宝根证书（.crt格式）'))
        }
        return Promise.resolve()
      }
    }]
  }
})

// 当前的form
const formRef = ref()

function getConfigParams(){
  return formRef.value.validate().then( () => {
    return convertEncryData()
  })

}

// 转换加密数据
function convertEncryData(){

  // 对象克隆
  let result = Object.assign({}, vdata.currentConfig)
  Object.keys(vdata.encryptionField).forEach(key => {
    // 加密数据 && 空串
    if (!result[key]) {
      delete result[key]
    }
  })

  return result
}

// 对外提供的页面的渲染函数 （ ifDefineArray = 接口的配置定义项数组，  currentConfig = 当前配置项 ）
// 20230918 新增： isProcessStarField = true ( 是否处理 脱敏数据， 默认为 true  )
function pageRender(ifDefineArray, currentConfig, mchType, isProcessStarField = true){

  // 赋值
  vdata.currentConfig = currentConfig

  // 处理加密数据字段
  if(isProcessStarField){
    Object.keys(vdata.encryptionField).forEach(key => {
      vdata.encryptionField[key] = vdata.currentConfig[key]
      delete vdata.currentConfig[key]
    })
  }

  // 重置form验证
  if (formRef.value !== undefined && formRef.value !== null) {
    formRef.value.resetFields()
  }

}

// 消除参数空格
function changeFun(value) {
  if(vdata.currentConfig[value]) {
    vdata.currentConfig[value] = vdata.currentConfig[value].trim()
  }
}

defineExpose({ getConfigParams, pageRender })

</script>
